require 'net/http'
require 'shellwords'

#
# http://brensche.de/brouter
#
class Brouter
    #Host = "h2096617.stratoserver.net"
    #BasePath = "/cgi-bin/brouter.sh?"

    def self.route_get(flat, flon, tlat, tlon)
			#qstr = "coords=%s_%s_%s_%s_..%%2Fcustomprofiles%%2F%s_0" % [flon, flat, tlon, tlat, profile]
			#Rails.logger.info BasePath + qstr
			#Route.new Net::HTTP.get(Host, BasePath + qstr)
			generate(flat, flon, tlat, tlon)
			Route.new open(Rails.root.to_s + "/tmp/brouter/mytrack0.gpx").read
    end

    def self.generate(flat, flon, tlat, tlon, profile = 'mtb1')
			File.unlink(Rails.root.to_s + "/tmp/brouter/mytrack0.gpx") if File.exists?(Rails.root.to_s + "/tmp/brouter/mytrack0.gpx")
			cmd = "ulimit -t 10;"+
				"cd #{Rails.root.to_s}/tmp/brouter && java -Xmx64M -Xms64M -Xmn8M -DmaxRunningTime=1800 "+
				"-DprofileBaseDir=#{Rails.root.to_s}/config/brouter -jar #{Rails.root.to_s}/vendor/brouter/brouter64.jar "+
				"#{Rails.root.to_s}/db/brouter %s %s %s %s %s" % [
					Shellwords.escape(flon), Shellwords.escape(flat),
					Shellwords.escape(tlon), Shellwords.escape(tlat), Shellwords.escape(profile)
				]
			system(cmd << " >>#{Rails.root.to_s}/log/brouter.log")
			Rails.logger.info "Brouter return value: %d" % $?.exitstatus
			raise "brouter failed" unless $?.exitstatus.zero? and File.exists?("#{Rails.root.to_s}/tmp/brouter/mytrack0.gpx")
    end

    class Route
			def initialize(answer)
					@a = Nokogiri::XML(answer)
			end

			def coordinates
					ret = []
					@a.search('trkpt').each{|pt|
							ret << "%s,%s" % [pt['lon'],pt['lat']]
					}
					ret
			end

			def distance
					false
			end

			def traveltime
					false
			end
    end
end
